package com.cfets.annualAssessment.securityConfig;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by ShenYiChou on 2017/10/17.
 */
@Service
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if(!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            response.setContentType("text/html;charset=utf-8;application/x- www-form-urlencoded");
            try {
                HttpSession session = request.getSession(false);
                String validCode = this.obtainCode(request);
                String saveCode = (String)session.getAttribute("validate_code");
                if(session == null||saveCode==null) {
                    this.getFailureHandler().onAuthenticationFailure(request,response,new AuthenticationServiceException("verifyCode is wrong"));
                    return null;
                }
                if(!(saveCode != null && saveCode.equals(validCode))) {
                        this.getFailureHandler().onAuthenticationFailure(request,response,new AuthenticationServiceException("verifyCode is wrong"));
                    return null;
                }
                session.removeAttribute("validate_code");//验证成功
            } catch (IOException | ServletException e) {
                e.printStackTrace();
            }

            String username = this.obtainUsername(request);
            String password = this.obtainPassword(request);

            if(username == null) {
                username = "";
            }

            if(password == null) {
                password = "";
            }

            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

    protected String obtainCode(HttpServletRequest request) {
        return request.getParameter("verifyCode");
    }
}
